/*
 * @Author: 鱿鱼溪学院
 * @Date: 2025-11-08 00:40:22
 * @LastEditTime: 2025-11-08 15:47:06
 * @LastEditors: 鱿鱼溪学院
 * @Description: MySQL数据库连接池配置
 * @FilePath: \jmd-ser-ts\app\db\mysql.ts
 * Copyright 鱿鱼溪学院 by edu v1.0
 * 天道酬勤
 */
import { createPool, Pool } from "mysql2/promise";
import type { PoolOptions } from "mysql2/promise";

import dbConfig from "../../config/config.db";

/**
 * MySQL数据库连接池配置
 */
const poolConfig: PoolOptions = {
  host: dbConfig.db_host || "localhost",
  user: dbConfig.db_user || "root",
  password: dbConfig.db_pwd || "",
  database: dbConfig.db_name || "example_db",
  port: dbConfig.db_port ? Number(dbConfig.db_port) : 3306,
  waitForConnections: true,
  connectionLimit: dbConfig.pool?.max || 10,
  queueLimit: 0,
  // 使用连接池时，启用保持连接活跃
  enableKeepAlive: dbConfig.enableKeepAlive !== false,
  keepAliveInitialDelay: dbConfig.keepAliveInitialDelay || 10000,
};

/**
 * MySQL连接池实例
 */
let pool: Pool | null = null;

/**
 * 初始化数据库连接池
 */
export const initDatabase = async (): Promise<void> => {
  try {
    pool = createPool(poolConfig);

    // 测试连接
    const connection = await pool.getConnection();
    console.log("数据库连接成功");
    connection.release();
  } catch (error) {
    console.error("数据库连接失败:", error);
    throw error;
  }
};

/**
 * 获取数据库连接池
 */
export const getPool = (): Pool => {
  if (!pool) {
    throw new Error("数据库连接池未初始化，请先调用initDatabase()");
  }
  return pool;
};

/**
 * 执行SQL查询
 * @param sql SQL查询语句
 * @param params 查询参数
 */
export const query = async <T = any>(
  sql: string,
  params?: any[]
): Promise<T[]> => {
  const pool = getPool();
  const [rows] = await pool.execute(sql, params);
  return rows as T[];
};

/**
 * 关闭数据库连接池
 */
export const closeDatabase = async (): Promise<void> => {
  if (pool) {
    await pool.end();
    pool = null;
    console.log("数据库连接池已关闭");
  }
};
